--bucle d2,
if RFirst then
RFirst = 1;
else
RFirst = 2;
end
if RFirst == 2 then
RCount = 1;
end
if RFirst == 1 then
RCount = RCount+1;
end
if RCount > 2 then
RCount = 1
end
switch RCount 
case 1
--detiene la escucha si no detecta verbalización de parte del usuario
require "import"
import "android.content.Context"
import "android.content.Intent"
import "java.util.Locale"

import "android.speech.SpeechRecognizer"
import "android.speech.RecognitionListener"
import "android.speech.RecognizerIntent"
import "java.util.Locale"
import "android.content.Intent"

local substitutionTable = {
    ["chino"] = "Jieshuo"
}

function capitalizeFirstWord(text)
    local firstChar = text:sub(1, 1)
    local restOfString = text:sub(2)
    return firstChar:upper() .. restOfString
end

function substituteWords(text)
    for word, substitution in pairs(substitutionTable) do
        text = text:gsub("%f[%a]" .. word .. "%f[%A]", substitution)
    end
    return text
end

function capitalizeAfterPeriod(text)
    return text:gsub("(%.[%s%p]*%a)", function(match)
        local char = match:sub(-1)
        local capitalizedChar = char:upper()
        return match:sub(1, -2) .. capitalizedChar
    end)
end

function addPunctuation(text)
    local lastChar = text:sub(-1)
    local punctuation = { ".", "!", "?" }
    local hasPunctuation = false

    for _, p in ipairs(punctuation) do
        if lastChar == p then
            hasPunctuation = true
            break
        end
    end

    if not hasPunctuation then
        text = text .. "."
    end

    return text
end
function hasInternetConnection()
    local connectivityManager = this.getSystemService(Context.CONNECTIVITY_SERVICE)
    local networkInfo = connectivityManager.getActiveNetworkInfo()
    return networkInfo ~= nil and networkInfo.isConnected()
end

function kill()
    speechRecognizer.destroy()
    speechRecognizer = nil
    return true
end

function startListening()
    if not hasInternetConnection() then
        -- No hay conexión a Internet, no se puede realizar el reconocimiento de voz
        service.asyncSpeak("No hay conexión a Internet. El reconocimiento de voz no está disponible.")
        return false
    end
    
    local verbalizationDetected = false
    
    speechRecognizer = SpeechRecognizer.createSpeechRecognizer(this)
    speechListener = RecognitionListener{
        onResults = function(results)
            data = results.getParcelableArrayList(SpeechRecognizer.RESULTS_RECOGNITION)
            if data ~= nil and data.size() > 0 then
                -- Se ha detectado alguna verbalización
                verbalizationDetected = true
                local recognizedText = data.get(0)
                recognizedText = capitalizeFirstWord(recognizedText)
                recognizedText = substituteWords(recognizedText)
                recognizedText = capitalizeAfterPeriod(recognizedText)
                recognizedText = addPunctuation(recognizedText)
                recognizedText = string.gsub(recognizedText, "(%s?)coma(%s?)([%p]*)$", "%2,%3")
                recognizedText = string.gsub(recognizedText, "(%s?)punto(%s?)([%p]*)$", "%2.%3")
                recognizedText = string.gsub(recognizedText, "(%s?)interrogación(%s?)([%p]*)$", "%2?")
                recognizedText = string.gsub(recognizedText, "(%s?)dos puntos(%s?)([%p]*)$", "%2:")
                recognizedText = string.gsub(recognizedText, "(%s?)comillas(%s?)([%p]*)$", "%2\"")
                recognizedText = string.gsub(recognizedText, "(%s?)Comillas(%s?)([%p]*)$", "%2\"")
service.paste(recognizedText .. "\n")
                service.speak(recognizedText)
            end
            -- Si no se detectó ninguna verbalización en el primer intento, detener reconocimiento de voz
            if not verbalizationDetected then
                kill()
                return false
            end
        end,
        onError = function()
            -- Ocurrió un error, detener reconocimiento de voz
            kill()
            return false
        end
    }
    
    recognizerIntent = Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH)
    recognizerIntent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL, RecognizerIntent.LANGUAGE_MODEL_FREE_FORM)
    recognizerIntent.putExtra(RecognizerIntent.EXTRA_LANGUAGE, Locale.getDefault())
    recognizerIntent.putExtra(RecognizerIntent.EXTRA_CALLING_PACKAGE, this.getPackageName())
    speechRecognizer.startListening(recognizerIntent)
    speechRecognizer.setRecognitionListener(speechListener)
    
    return true
end

startListening()
case 2
if service.click({
{"Aceptar",
"Aceptar|Enviar",
"Enviar",
}
})
return true
end


end
return true